<?php

namespace App\Http\Controllers\Crm;

use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\Customer;
use App\Models\CustomerField;
use App\Models\CustomerFieldValue;
use App\Models\CustomerPrice;
use App\Models\CustomerRemark;
use App\Models\Department;
use App\Models\Node;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class CustomerController extends Controller
{

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = $request->all([
                'uuid',
                'name',
                'contact_name',
                'contact_phone',
                'node_id',
                'follow_time_start',
                'follow_time_end',
                'follow_user_id',
                'type',
                'is_end',
            ]);
            $user = $request->user();
            $res = Customer::query()
                ->where(function ($query) use ($user) {
                    if ($user->hasPermissionTo('crm.customer.list_all')) {
                        return $query->where('owner_user_id', '>', 0);
                    } elseif ($user->hasPermissionTo('crm.customer.list_department_sub')) {
                        $departmentIds = Department::query()->where('parent_id',$user->department_id)->pluck('id')->toArray();
                        $departmentIds = array_merge($departmentIds,[$user->department_id]);
                        return $query->whereIn('owner_department_id', $departmentIds);
                    } elseif ($user->hasPermissionTo('crm.customer.list_department')) {
                        return $query->where('owner_department_id', '=', $user->department_id);
                    } else {
                        return $query->where('owner_user_id', $user->id);
                    }
                })
                ->where('status', '=', 3)
                //客户编号
                ->when($data['uuid'], function ($query) use ($data) {
                    return $query->where('uuid', $data['uuid']);
                })
                //客户名称
                ->when($data['name'], function ($query) use ($data) {
                    return $query->where('name', $data['name']);
                })
                //联系电话
                ->when($data['contact_phone'], function ($query) use ($data) {
                    return $query->where('contact_phone', $data['contact_phone']);
                })
                //联系人
                ->when($data['contact_name'], function ($query) use ($data) {
                    return $query->where('contact_name', $data['contact_name']);
                })
                //类型
                ->when($data['type'], function ($query) use ($data) {
                    return $query->where('type', $data['type']);
                })
                //节点
                ->when($data['node_id'], function ($query) use ($data) {
                    return $query->where('node_id', $data['node_id']);
                })
                //跟进时间
                ->when($data['follow_time_start'] && !$data['follow_time_end'], function ($query) use ($data) {
                    return $query->where('follow_time', '>=', $data['follow_time_start']);
                })
                ->when(!$data['follow_time_start'] && $data['follow_time_end'], function ($query) use ($data) {
                    return $query->where('follow_time', '<=', $data['follow_time_end']);
                })
                ->when($data['follow_time_start'] && $data['follow_time_end'], function ($query) use ($data) {
                    return $query->whereBetween('follow_time', [$data['follow_time_start'], $data['follow_time_end']]);
                })
                //跟进人
                ->when($data['follow_user_id'], function ($query) use ($data) {
                    return $query->where('follow_user_id', $data['follow_user_id']);
                })
                ->when($data['is_end'] !== null, function ($query) use ($data) {
                    return $query->where('is_end', $data['is_end']);
                })
                ->orderBy('is_end', 'asc')
                ->orderBy('status_time', 'desc')
                ->paginate($request->get('limit', 30));
            return $this->success('ok', $res->items(), $res->total());
        }
        return View::make('crm.customer.index');
    }


    public function create()
    {
        $fields = CustomerField::query()
            ->where('visiable', 1)
            ->orderBy('sort', 'asc')
            ->get();
        return View::make('crm.customer.create', compact('fields'));
    }


    public function store(Request $request)
    {
        $user = $request->user();
        $data = $request->all(['name', 'contact_name', 'contact_phone', 'type']);
        //验证手机号码
        $exsit = Customer::query()->where('contact_phone',$data['contact_phone'])->count();
        if ($exsit){
            return $this->error('联系电话已经存在');
        }
        $dataInfo = [];
        $fields = CustomerField::query()->where('visiable', '=', 1)->get();
        foreach ($fields as $d) {
            $items = [
                'customer_field_id' => $d->id,
                'data' => $request->get($d->field_key),
            ];
            if ($d->field_type == 'checkbox') {
                if (!empty($items['data'])) {
                    $items['data'] = implode(',', $items['data']);
                } else {
                    $items['data'] = null;
                }
            }
            array_push($dataInfo, $items);
        }
        DB::beginTransaction();
        try {
            $customer_id = DB::table('customer')->insertGetId([
                'uuid' => create_num('kh'),
                'name' => $data['name'],
                'contact_name' => $data['contact_name'],
                'contact_phone' => $data['contact_phone'],
                'type' => $data['type'],
                'created_user_id' => $user->id,
                'created_user_nickname' => $user->nickname,
                'owner_user_id' => $user->id,
                'owner_user_nickname' => $user->nickname,
                'owner_department_id' => $user->department_id ?? 0,
                'assignment_user_id' => 0,
                'assignment_user_nickname' => null,
                'assignment_time' => null,
                'status' => 3,
                'source' => 3,
                'status_time' => date('Y-m-d H:i:s'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            foreach ($dataInfo as $d) {
                DB::table('customer_field_value')->insert([
                    'customer_id' => $customer_id,
                    'customer_field_id' => $d['customer_field_id'],
                    'data' => $d['data'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('客户录入个人库异常：' . $exception->getMessage());
            return $this->error();
        }
    }


    public function edit(Request $request, $id)
    {
        $model = Customer::query()->findOrFail($id);
        $fields = CustomerField::query()
            ->where('visiable', 1)
            ->orderBy('sort', 'asc')
            ->get();
        $model->contact_phone_encode = !$request->user()->hasPermissionTo('dataPem.phone') ? $model->contact_phone : $this->phoneEncode($model->contact_phone);
        $data = CustomerFieldValue::query()->where('customer_id', '=', $model->id)->pluck('data', 'customer_field_id')->toArray();
        return View::make('crm.customer.edit', compact('model', 'fields', 'data'));
    }


    public function update(Request $request, $id)
    {
        $data = $request->all([
            'name',
            'contact_name',
            'contact_phone',
            'type'
        ]);
        $dataInfo = [];
        $fields = CustomerField::query()->where('visiable', '=', 1)->get();
        foreach ($fields as $d) {
            $items = [
                'customer_field_id' => $d->id,
                'data' => $request->get($d->field_key),
            ];
            if ($d->field_type == 'checkbox') {
                if (!empty($items['data'])) {
                    $items['data'] = implode(',', $items['data']);
                } else {
                    $items['data'] = null;
                }
            }
            array_push($dataInfo, $items);
        }

        DB::beginTransaction();
        try {
            DB::table('customer')->where('id', $id)->update([
                'name' => $data['name'],
                'contact_name' => $data['contact_name'],
                'contact_phone' => $data['contact_phone'],
                'type' => $data['type'],
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            foreach ($dataInfo as $d) {
                DB::table('customer_field_value')
                    ->updateOrInsert([
                        'customer_id' => $id,
                        'customer_field_id' => $d['customer_field_id'],
                    ], [
                        'data' => $d['data'],
                    ]);
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('更新个人库客户异常：' . $exception->getMessage());
            return $this->error();
        }
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids');
        try {
            Customer::query()->whereIn('id', $ids)->delete();
            return $this->success();
        } catch (\Exception $exception) {
            Log::error('删除个人库客户异常：' . $exception->getMessage());
            return $this->error();
        }
    }

    public function transfer(Request $request)
    {
        $ids = $request->get('ids', []);
        $user = User::where('id', $request->get('user_id'))->first();
        if ($user == null) {
            return $this->error('请选择员工');
        }
        DB::beginTransaction();
        try {
            $data = [
                'owner_user_id' => $user->id,
                'owner_user_nickname' => $user->nickname,
                'owner_department_id' => $user->department_id ?? 0,
                'source' => 4,
            ];
            Customer::query()->whereIn('id', $ids)->update($data);
            push_message(
                'msg',
                ['title' => '移交客户提醒', 'content' => '用户 ' . $request->user()->nickname . ' 移交给你 ' . count($ids) . ' 个客户至你的个人库'],
                [$user->id]
            );
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('移交异常：' . $exception->getMessage());
            return $this->error();
        }
    }


    public function remove(Request $request)
    {
        $customer_ids = $request->input('customer_ids');
        if (!is_array($customer_ids) || empty($customer_ids)) {
            return $this->error('请选择剔除项');
        }
        try {
            Customer::query()->whereIn('id', $customer_ids)->update([
                'status' => 5,
                'status_time' => date('Y-m-d H:i:s'),
                'owner_user_id' => 0,
                'owner_user_nickname' => null,
                'owner_department_id' => 9,
            ]);
            return $this->success();
        } catch (\Exception $exception) {
            Log::error('剔除客户异常：' . $exception->getMessage());
            return $this->error();
        }
    }

    public function remark(Request $request, $id)
    {
        $customer = Customer::query()->where('id', '=', $id)->first();
        $nodes = Node::query()->whereIn('type', [1, 2])->orderBy('sort', 'asc')->get();

        if ($request->ajax()) {
            $data = $request->all(['node_id', 'content', 'next_follow_time', 'type']);
            $old_node_id = $customer->node_id;
            $old_node_name = null;
            $new_node_id = $data['node_id'] ?? 0;
            $new_node_name = null;
            foreach ($nodes as $node) {
                if ($node->id == $old_node_id) {
                    $old_node_name = $node->name;
                }
                if ($node->id == $new_node_id) {
                    $new_node_name = $node->name;
                }
            }
            DB::beginTransaction();
            try {
                $customer->update([
                    'follow_time' => date('Y-m-d H:i:s'),
                    'node_id' => $new_node_id,
                    'node_name' => $new_node_name,
                    'follow_user_id' => $request->user()->id,
                    'follow_user_nickname' => $request->user()->nickname,
                    'next_follow_time' => $data['next_follow_time'],
                    'remark' => $data['content'],
                    'type' => $data['type'],
                ]);
                CustomerRemark::create([
                    'customer_id' => $customer->id,
                    'old_node_id' => $old_node_id,
                    'old_node_name' => $old_node_name,
                    'new_node_id' => $new_node_id,
                    'new_node_name' => $new_node_name,
                    'content' => $data['content'],
                    'next_follow_time' => $data['next_follow_time'],
                    'user_id' => $request->user()->id,
                    'user_nickname' => $request->user()->nickname,
                ]);
                DB::commit();
                return $this->success();
            } catch (\Exception $exception) {
                DB::rollBack();
                Log::error('备注跟进客户异常：' . $exception->getMessage());
                return $this->error();
            }

        }
        return View::make('crm.customer.remark', compact('customer', 'nodes'));
    }


    public function show(Request $request, $id)
    {
        $model = Customer::with('fields')->where('id', '=', $id)->first();
        $model->contact_phone_encode = $request->user()->hasPermissionTo('dataPem.phone') ? $model->contact_phone : $this->phoneEncode($model->contact_phone);

        return View::make('crm.customer.show', compact('model'));
    }

    /**
     * 成单（签合同）
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function contract(Request $request,$id)
    {
        $model = Customer::query()->where('id', '=', $id)->firstOrFail();
        if ($request->ajax()) {
            $data = $request->all([
                'stime',
                'etime',
                'total_money',
                'payed_money',
                'multiple_file',
                'remark',
            ]);
            DB::beginTransaction();
            try {
                $data = array_merge($data,[
                    'customer_id' => $model->id,
                    'num' => create_num('ht'),
                    'owner_department_id' => $request->user()->department_id,
                    'owner_user_id' => $request->user()->id,
                    'owner_user_nickname' => $request->user()->nickname,
                ]);
                Contract::create($data);
                if ($model->is_end != 1){
                    $model->update([
                        'is_end' => 1,
                        'end_time' => date('Y-m-d H:i:s'),
                    ]);
                }
                DB::commit();
                return $this->success('操作成功，请等待管理员审核');
            }catch (\Exception $exception){
                DB::rollBack();
                Log::error('生成合同异常:'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('crm.customer.contract', compact('model'));
    }

    // 下单（订单）
    public function order(Request $request,$id)
    {
        $model = Customer::query()->where('id', '=', $id)->firstOrFail();
        if ($request->ajax()) {
            $data = $request->all([
                'stime',
                'etime',
                'total_money',
                'payed_money',
                'multiple_file',
                'remark',
                'product_ids',
                'pay_type',
                'first_money',
                'mid_money',
                'last_money',
            ]);
            DB::beginTransaction();
            try {
                $data = array_merge($data,[
                    'customer_id' => $model->id,
                    'num' => create_num('dd'),
                    'owner_department_id' => $request->user()->department_id,
                    'owner_user_id' => $request->user()->id,
                    'owner_user_nickname' => $request->user()->nickname,
                ]);
                Order::create($data);
                DB::commit();
                return $this->success('操作成功，请等待管理员审核');
            }catch (\Exception $exception){
                DB::rollBack();
                Log::error('生成订单异常:'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('crm.customer.order',compact('model'));
    }

}
